package org.zhouhe.modules.report.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.zhouhe.base.BaseService;
import org.zhouhe.page.PageUtil;
import org.zhouhe.vo.Industry;
import org.zhouhe.vo.Keyword;
import org.zhouhe.vo.KeywordRecommended;
import org.zhouhe.vo.Report;
import org.zhouhe.vo.ReportIndustry;
import org.zhouhe.vo.ReportReco;
import org.zhouhe.vo.ReportType;

@Service
@SuppressWarnings("unchecked")
public class ReportService extends BaseService {
	public List<ReportType> getReportTypeList() {
		return dao.find("from ReportType");
	}

	public void save(Report report) {
		//report.setReportIndustries(report.getReportIndustries());
		for(ReportIndustry inds:report.getReportIndustries()){
			inds.setReport(report);
		}
		for(ReportReco reco:report.getReportRecos()){
			if(reco != null){
				reco.setReport(report);
			}
		}
		report.setCreateTime(new Timestamp(new Date().getTime()));
		report.setUpdateTime(new Timestamp(new Date().getTime()));
		report.setStatus(1);
		dao.save(report);
	}

	public void update(Report report) {
		dao.executeUpdate("delete from ReportIndustry where report.reportId="+ report.getReportId());
		dao.executeUpdate("delete from ReportReco where report.reportId="+ report.getReportId());
		Report reportBean = (Report) dao.get(Report.class, report.getReportId());
		reportBean.setReportType(report.getReportType());
		reportBean.setSummary(report.getSummary());
		reportBean.setTitle(report.getTitle());
		reportBean.setCatalog(report.getCatalog());
		reportBean.setKeywords(report.getKeywords());
		reportBean.setRecommended(report.getRecommended());
		reportBean.setRecommendTips(report.getRecommendTips());
		reportBean.setImgName(report.getImgName());
		reportBean.setDisplayTime(report.getDisplayTime());
		reportBean.setFree(report.getFree());
		
		reportBean.setPricePaper(report.getPricePaper());
		reportBean.setPriceElectron(report.getPriceElectron());
		reportBean.setPriceTotal(report.getPriceTotal());
		reportBean.setPublishInstitution(report.getPublishInstitution());
		reportBean.setPublishDate(report.getPublishDate());
		reportBean.setManifestations(report.getManifestations());
		reportBean.setOrderTel(report.getOrderTel());
		reportBean.setDeliveryTime(report.getDeliveryTime());
		reportBean.setDeliveryMethod(report.getDeliveryMethod());
		reportBean.setFax(report.getFax());
		
		reportBean.setReportIndustries(report.getReportIndustries());
		for(ReportIndustry inds:reportBean.getReportIndustries()){
			inds.setReport(reportBean);
		}
		reportBean.setReportRecos(report.getReportRecos());
		for(ReportReco reco:reportBean.getReportRecos()){
			if(reco != null){
				reco.setReport(reportBean);
			}
		}
		dao.update(reportBean);
	}

	public void delete(Report report) {
		dao.delete(report);
	}

	public Report getReportDetail(Integer reportId) {
		Report reportBean = (Report) dao.get(Report.class, reportId);
		return reportBean;
	}

	public PageUtil getReportList(PageUtil pageUtil, Report report, Integer industryId, Integer typeId) {
		if (pageUtil == null) {
			pageUtil = new PageUtil();
		}
		List<Object> paramList = new ArrayList<Object>();
		String select = "select distinct r ";
		StringBuilder from = new StringBuilder();
		from.append("from Report r left join r.reportIndustries ri where r.status=1 ");
		if (report == null) {
			report = new Report();
		}
		// 文章类型：
		if (typeId != null && typeId > 0) {
			from.append(" and r.reportType.idPath like ? ");
			paramList.add("%|"+ typeId +"|%");
		}
		// 所属行业：
		if (industryId != null && industryId > 0) {
			from.append(" and ri.industry.idPath like ? ");
			paramList.add("%|"+ industryId + "|%");
		}
		//免费报告:
		if (report.getFree() != null) {
			from.append(" and r.free=? ");
			paramList.add(report.getFree());
		}
		//有缩微图
		if("required".equalsIgnoreCase(report.getImgName())){
			from.append(" and r.imgName is not null and length(trim(r.imgName))>0 ");
		}
		// 关键字：
		if (report.getTitle() != null && !"".equals(report.getTitle().trim())) {
			String[] keys = report.getTitle().replaceAll("[ ]+", "").split(",");
//			from.append(" and (r.title like ? or r.summary like ?) ");
			List<String> lst = new ArrayList<String>();
			for(String key : keys){
				lst.add(" (r.title like ? or r.summary like ?) ");
				paramList.add("%" + key + "%");
				paramList.add("%" + key + "%");
				System.out.println("key:"+key);
			}
			if(lst.size() > 0){
				from.append(" and ( "+ StringUtils.join(lst, " or ") +" ) ");
			}
		}
		from.append(" order by r.createTime desc, r.reportId desc");
		pageUtil.setHQL(select, from.toString(), paramList);
		return dao.findByPage(pageUtil);
	}

	public List<Report> getReportByType(Integer typeId, Integer industryId, Integer count, boolean recommendedFirst) {
		List<Report> reportList = new ArrayList<Report>();
//		String hql = "from Report r left join ReportIndustry ri on r.reportId=ri.report.reportId where r.status=1 and r.reportType.idPath like '%|" + typeId + "|%' ";
		String hql = "select distinct r from Report r left join r.reportIndustries ri where r.status=1 and r.free=0 and r.reportType.idPath like '%|" + typeId + "|%' ";
		
		if (industryId != null) {
			hql += " and ri.industry.idPath like '%|"+ industryId +"|%'  ";
		}
		String orderBy = " order by r.createTime desc, r.reportId desc";
		String s = "";
		if (recommendedFirst) {
			Query query = dao.getSessionFactory().getCurrentSession().createQuery(hql + " and r.recommended=1"+ orderBy);
			query.setMaxResults(1);
			List<Report> recommendedLst = query.list();
			if (recommendedLst.size() == 1) {
				reportList.addAll(recommendedLst);
				count--;
				s = " and r.reportId !=" + recommendedLst.get(0).getReportId();
			}
		}

		Query query = dao.getSessionFactory().getCurrentSession().createQuery(hql + s + orderBy);
		query.setMaxResults(count);
		List<Report> dataLst = query.list();
		reportList.addAll(dataLst);
		return reportList;
	}
	
	/**
	 * 查询通过图片推荐的报告，以图片幻灯的形式展现。
	 * @param typeId
	 * @param industryId
	 * @param count
	 * @return
	 */
	public List<Report> getReportsRecoByImage(Integer typeId, Integer industryId, Integer count){
		StringBuilder hql = new StringBuilder();
		hql.append("select distinct r from Report r left join r.reportIndustries i where r.status=1 and r.free=0 ");
		if(typeId != null){
			hql.append(" and r.reportType.idPath like '%|"+ typeId +"|%' ");
		}
		if(industryId != null){
			hql.append(" and i.industry.idPath like '%|"+ industryId +"|%' ");
		}
		hql.append(" and r.imgName is not null and r.imgName != ''");
		hql.append(" order by r.createTime desc, r.reportId desc ");
		Query query = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		query.setMaxResults(count);
		List<Report> dataLst = query.list();
		return dataLst;
	}

	public List<Report> getFreeReports(Integer typeId, Integer industryId, Integer count) {
		StringBuilder hql = new StringBuilder();
		hql.append(" select distinct r ");
		hql.append(" from Report r left join r.reportIndustries ri ");
		hql.append(" where r.status=1 and r.free=1 ");
		if(typeId != null){
			hql.append(" and r.reportType.idPath like '%|"+ typeId +"|%'" );
		}
		if(industryId != null){
			hql.append(" and ri.industry.idPath like '%|"+ industryId +"|%'" );
		}
		hql.append(" order by r.createTime desc, r.reportId desc ");
		Query query = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		query.setMaxResults(count);
		List<Report> dataLst = query.list();
		return dataLst;
	}

	public ReportType getReportType(Integer typeId) {
		return (ReportType) dao.get(ReportType.class, typeId);
	}

	/**
	 * 二级行业首页（报告类型ID已经确定）
	 * 
	 * @param typeId
	 * @param industryId
	 * @param count
	 * @return
	 */
	public Industry getReport4Industry1(Integer typeId, Integer industryId, Integer count) {
		Industry ind = (Industry) dao.get(Industry.class, industryId);
		Set<Industry> industrySet = ind.getIndustries();
		for (Industry indu : industrySet) {
			String hql = "select distinct r from Report r left join r.reportIndustries i where r.status=1 and r.free=0 and r.reportType.idPath like '%|" + typeId + "|%' and i.industry.idPath like '%|" + indu.getIndustryId() +"|%'";
			hql += " order by r.createTime desc, r.reportId desc";
			Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql);
			q.setMaxResults(count);
//			indu.setReports(new HashSet(q.list()));
			List<Report> reportList = q.list();
			Set<ReportIndustry> reportIndustries = new LinkedHashSet<ReportIndustry>();
			for(Report rpt:reportList){
				ReportIndustry ri = new ReportIndustry();
				ri.setReport(rpt);
				reportIndustries.add(ri);
			}
			indu.setReportIndustries(reportIndustries);
		}
		return ind;
	}
	public void updateKeywordOrder(List<KeywordRecommended> keywordRecommendedList){
		for(KeywordRecommended keyword:keywordRecommendedList){
			dao.executeUpdate("update KeywordRecommended set orderId="+ keyword.getOrderId() +" where keywordRecommendedId="+ keyword.getKeywordRecommendedId());
		}
	}
	public void updateKeywordHits(String word){
		List<Object> list = dao.find("from Keyword where words=?", new Object[]{ word });
		if(list.size()>0){
			for(int i=0; i<list.size(); i++){
				Keyword key = (Keyword) list.get(i);
				key.setHits(key.getHits()+1);
				dao.update(key);
			}
		}else{
			Keyword key = new Keyword();
			key.setHits(1);
			key.setWords(word);
			dao.save(key);
		}
	}
	
	public void saveOrUpdateKeywordReco(KeywordRecommended keywordRecommended){
		if(keywordRecommended.getKeywordRecommendedId() != null){
			KeywordRecommended key = (KeywordRecommended) dao.get(KeywordRecommended.class, keywordRecommended.getKeywordRecommendedId());
			key.setWords(keywordRecommended.getWords());
			dao.update(key);
		}else{
			dao.save(keywordRecommended);
		}
	}
	public void deleteKeyword(KeywordRecommended keywordRecommended){
		dao.executeUpdate("delete from KeywordRecommended where keywordRecommendedId="+ keywordRecommended.getKeywordRecommendedId());
	}
	public List<KeywordRecommended> getKeyWordsRecommended(Integer count){
		String hql = " from KeywordRecommended order by orderId";
		Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		if(count != null && count > 0){
			q.setMaxResults(count);
		}
		return q.list();
	}
	public PageUtil getKeywordList(PageUtil pageUtil, String words, Integer recommended, Boolean orderByHits){
		if (pageUtil == null) {
			pageUtil = new PageUtil();
		}
		List<Object> paramList = new ArrayList<Object>();
		StringBuilder from = new StringBuilder();
		from.append("from Keyword where 1=1 ");
		// 关键字模糊查询：
		if (words != null && words.trim().length() > 0) {
			from.append(" and words like ? ");
			paramList.add("%"+ words.trim() +"%");
		}
		// 推荐：
		if (recommended != null) {
			from.append(" and recommended= ? ");
			paramList.add(recommended);
		}
		//结果排序:
		if (orderByHits != null) {
			from.append(" order by hits DESC, orderId ASC, keywordId ASC ");
		}else{
			from.append(" order by orderId ASC, keywordId ASC");
		}
		
		pageUtil.setHQL("", from.toString(), paramList);
		return dao.findByPage(pageUtil);
	}
}
